"""
Module to compare two signals

Functions
---------
`pearsonr`: Return the Pearson similitude between two signals.

"""
#
# pearson.py
#
# Copyright (C) 2012 Robert Buj Gelonch
# Copyright (C) 2012 David Megias Jimenez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
__author__ = "Robert Buj Gelonch, and David Megias Jimenez"
__copyright__ = "Copyright 2012, Robert Buj Gelonch and David Megias Jimenez"
__credits__ = ["Robert Buj Gelonch", "David Megias Jimenez"]
__license__ = "GPL"
__version__ = "3"
__maintainer__ = "Robert Buj"
__email__ = "rbuj@uoc.edu"
__status__ = "Development"
__docformat__ = 'plaintext'

import numpy

def pearsonr(S, s):
    num_elems = min(len(S), len(s))
    #--------------------------------------------------------------
    # Dispersion and Mean of 1st Signal
    #--------------------------------------------------------------
    S_mean = numpy.mean(S, axis=0)
    S_diff = numpy.array(S) - S_mean
    # S_dispersion = sum(S_diff)
    #--------------------------------------------------------------
    # Dispersion and Mean of 2nd Signal
    #--------------------------------------------------------------
    s_mean = numpy.mean(s, axis=0)
    s_diff = numpy.array(s) - s_mean
    # s_dispersion = sum(s_diff)
    #--------------------------------------------------------------
    # NUM
    #--------------------------------------------------------------
    num = sum([S_diff[i] * s_diff[i] for i in range(num_elems)])
    #--------------------------------------------------------------
    # DEN
    #--------------------------------------------------------------
    den_S = (sum([d ** 2 for d in S_diff[:num_elems]])) ** 0.5
    den_s = (sum([d ** 2 for d in s_diff[:num_elems]])) ** 0.5
    den = den_S * den_s
    #--------------------------------------------------------------
    # Division
    #--------------------------------------------------------------
    if den == 0:
        return 0
    return ((num / den) + 1) / 2
